package com.tjetc.service.Impl;

import com.tjetc.common.JsonResult;
import com.tjetc.dao.CategoryMapper;

import com.tjetc.dao.DishMapper;
import com.tjetc.entity.Category;
import com.tjetc.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private DishMapper dishMapper;

    /***
     * 添加菜系
     * @param category
     * @return
     */
    @Override
    public int insert(Category category) {
        if(selectByName(category.getName()) != null) {
            throw new RuntimeException("类别名不能重复");
        }
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        return categoryMapper.insert(category);
    }

    /***
     * 删除菜系
     * @param id
     * @return
     */
    @Override
    public int deleteById(Integer id) {
        return categoryMapper.deleteById(id);
    }

    /***
     * id查询菜系
     * @param id
     * @return
     */
    @Override
    public Category select(Integer id) {
        return categoryMapper.select(id);
    }

    /***
     * 商家id查询该商家已有的菜系
     * @param id
     * @return
     */
    @Override
    public List<Category> selectByMerchantId(Integer id) {
        //根据店家id分组查菜系二级分类
        List<Integer> lists = dishMapper.selectCategoryById(id);
        //查询所有的二级分类名称
        List<Category> categories = categoryMapper.selectByList(lists);
        if(lists.size()!=categories.size()){
            throw new RuntimeException("二级分类和菜系数量不对等");
        }else{
            return categories;
        }
    }

    /***
     * 查询所有菜系
     * @return
     */
    @Override
    public JsonResult selectAll() {
        return new JsonResult(0, "", categoryMapper.selectAll());
    }

    /***
     * 更新菜系
     * @param type
     * @return
     */
    @Override
    public JsonResult update(Category type) {
        return new JsonResult(0, "", categoryMapper.update(type));
    }

    /***
     * 一级分类id查询菜系
     * @param typeId
     * @return
     */
    @Override
    public List<Category> selectByTypeId(Integer typeId) {
        return categoryMapper.selectBytype(typeId);
    }

    /***
     * 菜系名称查询菜系
     * @param name
     * @return
     */
    @Override
    public Category selectByName(String name) {
        return categoryMapper.selectByName(name);
    }


}
